import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CategoryEntity } from './entities/category.entity'
// import { CreateCategoryDto } from './dto/create-category.dto'

// export type ICategories = CategoryEntity & { children?: ICategories[] }

export interface ICategories extends CategoryEntity {
  children: ICategories[]
}

export class MenuTree {
  id: string | number
  category_name: string
  category_code: string
  category_desc: string
  category_order: string
  children: MenuTree[]
}

@Injectable()
export class CategoriesService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly repository: Repository<CategoryEntity>
  ) {}

  // create(createCategoryDto: CreateCategoryDto) {
  //   return 'This action adds a new category'
  // }

  async findAll({ level } = { level: 1 }) {
    const category = await this.repository
      .createQueryBuilder('category')
      .where('category.category_level = :category_level', { category_level: level })
      .getMany()

    category[0].children = await this.findOne(category[0].id)

    return category
  }

  /**
   * 根据 id 获取子菜单
   * @param id category id
   * @returns children
   */
  async findOne(id: number) {
    const children = await this.repository
      .createQueryBuilder('children')
      .where('children.parent_id = :parent_id', { parent_id: id })
      .andWhere('children.category_status = :category_status', { category_status: 1 })
      .getMany()

    const parentIds = []
    for (const item of children) {
      parentIds.push(item.id)
    }

    const third = await this.repository
      .createQueryBuilder('third')
      .where('third.parent_id in (:...parent_id)', { parent_id: parentIds })
      .getMany()

    for (const item of children) {
      item.children = []
      for (const t of third) {
        if (item.id === t.parent_id) {
          item.children.push(t)
        }
      }
    }

    return children
  }

  // update(id: number, updateCategoryDto: UpdateCategoryDto) {
  //   return `This action updates a #${id} category`
  // }

  remove(id: number) {
    return `This action removes a #${id} category`
  }
}
